package leeon.bbsbrower.actions;

import ipworks.IPWorksException;
import leeon.bbsbrower.util.HTMLUtil;
import leeon.bbsbrower.util.HTTPBean;

public class BBSConAction {
	
	public static final String URL_SAVE_DOC = Config.SERVER_URL + Config.SERVER_CGI + "bbssnd";
	
	public static final String URL_EDIT_DOC = Config.SERVER_URL + Config.SERVER_CGI + "bbsedit";
	
	
	/**
	 * 通过文章对象中的地址,获取文章内容,
	 * @param url
	 * @return
	 * @throws IPWorksException 
	 */
	public static String getDocContentByURL(String url) throws IPWorksException {
		HTTPBean http = HTTPBean.newInstance(Config.PROXY_SERVER, Config.PROXY_PORT, Config.PROXY_USER, Config.PROXY_PASSWORD);
		String content = http.get(url);
		String[] contents = HTMLUtil.findStrs(content, "<pre class=ansi>", "</pre>");
			
		if (contents != null && contents.length != 0) {
			StringBuffer sb = new StringBuffer();
			for (int i = 0; i < contents.length; i ++) {
					
				contents[i] = HTMLUtil.removeHtmlTag(contents[i]);
				contents[i] = HTMLUtil.dealImageTag(contents[i]);
					
				sb.append(contents[i]).append("☆──────────────────────────────────────☆\n\n");
			}
			return sb.toString();
		} else {
			return "文章不存在"; 
		}
	}
	
	/**
	 * 发表文章
	 * @return
	 * @throws IPWorksException 
	 * @throws ContentException 
	 */
	public static void saveDocContent(String board, String sign, String reply, String title, String text) throws IPWorksException, ContentException {
		HTTPBean http = HTTPBean.newInstance(Config.PROXY_SERVER, Config.PROXY_PORT, Config.PROXY_USER, Config.PROXY_PASSWORD);
			
		String url = URL_SAVE_DOC + "?";
		url += "board=" + board + "&";			
		url += "title=" + title + "&";
		
		text = text.replaceAll("\n", "%0A").replaceAll("\r", "%0D");
		url += "text=" + text + "&";
			
		if (sign != null)
			url += "signature=" + sign + "&";
		else
			url += "signature=1&";
		
		if (reply != null) {				
			url += "replymode=" + reply ;				
		} else
			url += "replymode=2";
			
		String content = http.get(url);
		if (content == null || content.indexOf("<meta http-equiv='Refresh' content='0; url=bbsdoc?board") == -1)
			throw new ContentException(content);
	}
		
	/**
	 * 编辑文章
	 * @return
	 * @throws IPWorksException 
	 * @throws ContentException 
	 */
	public static void editDocContent(String board, String text, String file) throws IPWorksException, ContentException {
		HTTPBean http = HTTPBean.newInstance(Config.PROXY_SERVER, Config.PROXY_PORT, Config.PROXY_USER, Config.PROXY_PASSWORD);
		String url = URL_EDIT_DOC + "?";
		url += "board=" + board + "&";
		url += "text=" + text + "&";
		url += "file=" + file + "&";
			
		url += "type=1";
			
		String content = http.get(url);
		if (content == null || content.indexOf("修改文章成功") == -1)
			throw new ContentException(content);
	}
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {
	}

}
